import random

from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.db.models import Q
from django.http import HttpResponse, Http404
from django.template import RequestContext
from django.shortcuts import get_object_or_404, render_to_response

from filters.sentences import XML_to_sentences
from filters.pos import XML_to_POS
from models import XMLFile, Sentence, WordTreeNode

def get_random_obj(model):
    n = model.objects.count()
    if n <1:
        raise Http404
    i = random.randint(0, n-1)
    return model.objects.all()[i]

def home(request):
    try:
        demo_sent = get_random_obj(Sentence)
    except Http404:
        demo_sent = None
    return render_to_response(
        'home.html', {"demo_sent": demo_sent},
        context_instance=RequestContext(request))

def sentence(request, filename, nb):
    file = get_object_or_404(XMLFile, name=filename)
    sentence = get_object_or_404(Sentence, nb=nb, file=file)
    return render_to_response('sentence.html', {'sentence':sentence})

def search(request):
    query_string = ''
    results = None
    if  not ('q' in request.GET) or not request.GET['q'].strip():
        return home(request)
    query_string = request.GET['q'].strip()
    query = Q(form= query_string) | Q(lemma=query_string)
    results = WordTreeNode.objects.filter(query)
    paginator = Paginator(results, 5)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1
    try:
        results = paginator.page(page)
    except (EmptyPage, InvalidPage):
        results = paginator.page(paginator.num_pages)

    return render_to_response(
        'search/results_words.html',
        {'query_string': query_string,
         'results':results,},
        context_instance=RequestContext(request))

